<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="存储桶" prop="bucket">
            <el-input v-model="queryParams.bucket" placeholder="请输入存储桶" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="文件类型" prop="fileType">
            <el-select v-model="queryParams.fileType" placeholder="文件类型" clearable>
              <el-option v-for="dict in file_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="文件名称" prop="fileName">
            <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="扩展名" prop="extension">
            <el-input v-model="queryParams.extension" placeholder="请输入扩展名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="审核状态" prop="auditStatus">
            <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
              <el-option v-for="dict in audit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:mediaFiles:remove']"
              >删除
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        :data="mediaFilesList"
        @selection-change="handleSelectionChange"
        @header-click="handleCellMouseEnter"
        v-bind:border="showborder"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="服务器ip" align="center" prop="serverUrl" v-if="columns[0].visible" />
        <el-table-column label="存储桶" align="center" prop="bucket" v-if="columns[1].visible" />
        <el-table-column label="存储地址" align="center" prop="filePath" v-if="columns[2].visible" />
        <el-table-column label="文件类型" align="center" prop="fileType" v-if="columns[3].visible">
          <template #default="scope">
            <dict-tag :options="file_type" :value="scope.row.fileType" />
          </template>
        </el-table-column>
        <el-table-column label="文件大小" align="center" prop="fileSize" v-if="columns[4].visible">
          <template #default="scope">
            <el-tag type="success">
              <div v-if="(1024 * 1024) > scope.row.fileSize && scope.row.fileSize > 0">{{ (scope.row.fileSize / (1024)).toFixed(2) }}KB</div>
              <div v-if="scope.row.fileSize > (1024 * 1024) && scope.row.fileSize < (1024 * 1024 * 1024)">
                {{ (scope.row.fileSize / (1024 * 1024)).toFixed(2) }}MB
              </div>
              <div v-if="scope.row.fileSize > (1024 * 1024 * 1024)">{{ (scope.row.fileSize / (1024 * 1024 * 1024)).toFixed(2) }}GB</div>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="文件名称" align="center" prop="fileName" v-if="columns[5].visible" />
        <el-table-column label="标签" align="center" prop="target" v-if="columns[7].visible" />
        <el-table-column label="扩展名" align="center" prop="extension" v-if="columns[8].visible" />
        <el-table-column label="审核状态" align="center" prop="auditStatus" v-if="columns[9].visible">
          <template #default="scope">
            <dict-tag :options="audit_status" :value="scope.row.auditStatus" />
          </template>
        </el-table-column>
        <el-table-column label="审核意见" align="center" prop="auditMind" v-if="columns[10].visible" />
        <el-table-column label="上传人" align="center" prop="userName" v-if="columns[12].visible" />
        <el-table-column label="所属学校" align="center" prop="schoolId" v-if="columns[13].visible" />
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[22].visible" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:mediaFiles:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:mediaFiles:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改文件管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-form ref="mediaFilesFormRef" :model="form" :rules="rules" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="6">
            <div v-if="form.fileType == 1">
              <el-form-item label="图片预览" prop="serverUrl">
                <div class="demo-image__preview">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="form.url"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="[form.url]"
                    :initial-index="4"
                    fit="cover"
                  />
                </div>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="服务器ip" prop="serverUrl">
              <el-input v-model="form.serverUrl" placeholder="请输入服务器ip" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="存储桶" prop="bucket">
              <el-input v-model="form.bucket" placeholder="请输入存储桶" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="form.fileName" placeholder="请输入文件名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16">
            <el-form-item label="存储地址" prop="filePath">
              <el-input v-model="form.filePath" placeholder="请输入存储地址" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="文件MD5" prop="fileId">
              <el-input v-model="form.fileId" placeholder="请输入文件MD5值" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签" prop="target">
              <el-input v-model="form.target" placeholder="请输入标签" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="扩展名" prop="extension">
              <el-input v-model="form.extension" placeholder="请输入扩展名" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属学校" prop="schoolId">
              <el-input v-model="form.schoolId" placeholder="请输入所属学校" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="审核状态" prop="auditStatus">
              <el-radio-group v-model="form.auditStatus">
                <el-radio v-for="dict in audit_status" :key="dict.value" :label="parseInt(dict.value)">{{dict.label}} </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审核意见" prop="auditMind">
              <el-input v-model="form.auditMind" placeholder="请输入审核意见" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属学校" prop="schoolId">
              <el-input v-model="form.schoolId" placeholder="请输入所属学校" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MediaFiles" lang="ts">
import {
    listMediaFiles,
    getMediaFiles,
    delMediaFiles,
    addMediaFiles,
    updateMediaFiles
} from '@/api/system/mediaFiles';
import {
        MediaFilesVO,
        MediaFilesQuery,
        MediaFilesForm
} from '@/api/system/mediaFiles/types';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
    const { file_type, audit_status } = toRefs<any>(proxy?.useDict('file_type', 'audit_status'));

const mediaFilesList = ref<MediaFilesVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const formLabelWidth = '120px';
const showborder = ref(false)

const queryFormRef = ref<ElFormInstance>();
const mediaFilesFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const initFormData: MediaFilesForm = {
                    fileId: undefined,
                    serverUrl: undefined,
                    bucket: undefined,
                    filePath: undefined,
                    fileType: undefined,
                    fileSize: undefined,
                    fileName: undefined,
                    fileMd5: undefined,
                    target: undefined,
                    extension: undefined,
                    auditStatus: undefined,
                    auditMind: undefined,
                    userId: undefined,
                    userName: undefined,
                    schoolId: undefined,
                    schoolName: undefined,
                    remark: undefined
}
const data = reactive<PageData<MediaFilesForm, MediaFilesQuery>>({
    form: {...initFormData},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
                        bucket: undefined,
                        fileType: undefined,
                        fileName: undefined,
                        extension: undefined,
                        auditStatus: undefined,
        params: {
        }
    },
    rules: {

    }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询文件管理列表 */
const getList = async () => {
    loading.value = true;
    const res = await listMediaFiles(queryParams.value);
        mediaFilesList.value = res.rows;
    total.value = res.total;
    loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
    form.value = {...initFormData};
        mediaFilesFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: MediaFilesVO[]) => {
    ids.value = selection.map(item => item.fileId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加文件管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: MediaFilesVO) => {
    reset();
    const _fileId = row?.fileId || ids.value[0]
    const res = await getMediaFiles(_fileId);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改文件管理";
}


/** 提交按钮 */
const submitForm = () => {
        mediaFilesFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.fileId) {
                await updateMediaFiles(form.value).finally(() =>  buttonLoading.value = false);
            } else {
                await addMediaFiles(form.value).finally(() =>  buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("修改成功");
            dialog.visible = false;
            await getList();
        }
    });
}

/** 删除按钮操作 */
const handleDelete = async (row?: MediaFilesVO) => {
    const _fileIds = row?.fileId || ids.value;
    await proxy?.$modal.confirm('是否确认删除文件管理编号为"' + _fileIds + '"的数据项？').finally(() => loading.value = false);
    await delMediaFiles(_fileIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
    proxy?.download('system/mediaFiles/export', {
        ...queryParams.value
    }, `mediaFiles_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
    getList();
});


/** 列信息 */
const columns = ref([
            {key: 0, label: `服务器ip`, visible: true},
            {key: 1, label: `存储桶`, visible: true},
            {key: 2, label: `存储地址`, visible: true},
            {key: 3, label: `1:图片 2:音频 3:视频 4:文件 5:其他`, visible: true},
            {key: 4, label: `文件大小`, visible: true},
            {key: 5, label: `文件名称`, visible: true},
            {key: 6, label: `文件id MD5值`, visible: true},
            {key: 7, label: `标签`, visible: true},
            {key: 8, label: `扩展名`, visible: true},
            {key: 9, label: `审核状态 0:待审核 1:通过 2：驳回`, visible: true},
            {key: 10, label: `审核意见`, visible: true},
            {key: 11, label: ``, visible: true},
            {key: 12, label: `上传人`, visible: true},
            {key: 13, label: `所属学校`, visible: true},
            {key: 14, label: `学校名称`, visible: true},
            {key: 15, label: `创建部门`, visible: true},
            {key: 16, label: `创建人`, visible: true},
            {key: 17, label: `创建时间`, visible: true},
            {key: 18, label: `修改人`, visible: true},
            {key: 19, label: `修改时间`, visible: true},
            {key: 20, label: `逻辑删除`, visible: true},
            {key: 21, label: `版本`, visible: true},
            {key: 22, label: `备注`, visible: true},
]);


function handleCellMouseEnter() {
    showborder.value = !showborder.value;
}
</script>
